<template>
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
            <el-input v-model="form.type" placeholder="小于255的数字"></el-input>
        </el-form-item>
        <el-form-item label="缩略图">
            <el-upload
                class="avatar-uploader"
                :action="upload.action"
                :data="upload.data"
                :headers="$store.getters['backend/header']"
                :show-file-list="false"
                :on-success="handleImageSuccess">
                <img v-if="form.thumb !== ''"
                     :src="form.thumb"
                     :preview-src-list="[form.thumb]"
                     class="avatar"
                     style="max-width:100%; height: auto"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div class="upload-tip" slot="tip">
                    <el-button size="small" type="danger" @click="form.thumb = ''">删除</el-button>
                </div>
            </el-upload>

            <el-upload
                v-show="false"
                class="content-image-uploader"
                :action="upload.action"
                :data="upload.data"
                :headers="$store.getters['backend/header']"
                :show-file-list="false"
                :on-success="handleContentImageSuccess">
            </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="content_raw">
            <quill-editor ref="editor" v-model="form.content_raw" :options="editorOptions"></quill-editor>
        </el-form-item>
        <el-form-item label="排序">
            <el-input-number v-model="form.sort" :min="0" :max="100" label="数字越大越靠前"></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
            <el-radio-group v-model="form.status">
                <el-radio-button :label="item.value" v-for="(item, index) in options.status" :key="index">
                    {{ item.label }}
                </el-radio-button>
            </el-radio-group>
        </el-form-item>
        <el-row>
            <el-col>
                <el-form-item label="公告开始时间" label-width="100px">
                    <el-date-picker
                        v-model="form.start_time"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="timestamp"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
            </el-col>
            <el-col>
                <el-form-item label="公告结束时间" label-width="100px">
                    <el-date-picker
                        v-model="form.end_time"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="timestamp"
                        placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
            </el-col>
        </el-row>

        <el-form-item label="红点开关">
            <el-radio-group v-model="form.red_dots_switch">
                <el-radio-button :label="0">关闭</el-radio-button>
                <el-radio-button :label="1">开启</el-radio-button>
            </el-radio-group>
        </el-form-item>

        <el-form-item label="红点开始时间" label-width="100px">
            <el-date-picker
                v-model="form.red_dots_start_time"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp"
                placeholder="选择日期时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="红点结束时间" label-width="100px">
            <el-date-picker
                v-model="form.red_dots_end_time"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp"
                placeholder="选择日期时间">
            </el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" :loading="loading" @click="submit">确定</el-button>
            <el-button @click="cancel">返回</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {quillEditor, Quill} from 'vue-quill-editor'
import { addQuillTitle } from '~/utils/vue-quill-editor-title.js'
import htmlEditButton from "quill-html-edit-button";
Quill.register({
    "modules/htmlEditButton": htmlEditButton,
});

export default {
    components: {
        quillEditor,
    },
    props: {
        data: {}
    },
    data() {
        return {
            loading: false,
            form: {},
            formDefault: {
                id: 0,
                title: '',
                type: 0,
                thumb: '',
                content: '',
                content_raw: '',
                sort: '',
                status: 1,
                red_dots_switch: 0,
                red_dots_start_time: '',
                red_dots_end_time: '',
            },
            rules: {
                title: [
                    {required: true, message: '请输入标题', trigger: 'blur'},
                ],
                // content_raw: [
                //     {required: true, message: '请输入内容', trigger: 'blur'},
                // ],
            },
            upload: {
                action: '/admin/api/upload',
                data: {
                    type: 'image',
                }
            },
            options: this.$store.state.notice.options,
            editorOptions: {
                modules: {
                    toolbar: {
                        container: [
                            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
                            // ['blockquote'], // 引用  代码块
                            [{ header: 1 }, { header: 2 }], // 1、2 级标题
                            // [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
                            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
                            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
                            [{ indent: '-1' }, { indent: '+1' }], // 缩进
                            // [{ direction: 'rtl' }], // 文本方向
                            [{ align: [] }], // 添加居中按钮
                            [{ color: [] }, { 'background': [] }], // 文字颜色按钮
                            ['image', 'link'], // 链接、图片、视频
                        ],
                        handlers: {
                            image: function(value) {
                                console.log("handlers", value)
                                if (value) {
                                    document.querySelector(".content-image-uploader input").click();
                                } else {
                                    this.quill.format('image', false);
                                }
                            }
                        }
                    },
                    htmlEditButton: {
                        msg: "在这里修改HTML代码，点击完成将替换编辑器的内容", //Custom message to display in the editor, default: Edit HTML here, when you click "OK" the quill editor's contents will be replaced
                        okText: "完成", // Text to display in the OK button, default: Ok,
                        cancelText: "取消", // Text to display in the cancel button, default: Cancel
                        // buttonHTML: "&lt;&gt;", // Text to display in the toolbar button, default: <>
                        buttonTitle: "Show HTML source", // Text to display as the tooltip for the toolbar button, default: Show HTML source
                        // syntax: true, // Show the HTML with syntax highlighting. Requires highlightjs on window.hljs (similar to Quill itself), default: false
                        // prependSelector: 'div#myelement', // a string used to select where you want to insert the overlayContainer, default: null (appends to body),
                        // editorModules: {} // The default mod
                    },
                },
                placeholder: '点击此处输入文本',
                // formats: ['bold', 'italic', 'underline', 'color', 'background', 'size'],
                // theme: 'bubble',
            }
        }
    },
    computed: {},
    watch: {
        data(newVal) {
            this.syncForm();
        }
    },
    methods: {
        getFormAction() {
            return this.form.id ? 'notice/Update' : 'notice/Store';
        },
        submit() {
            this.$refs.form.validate(valid => {
                if (!valid) return false;
                let form = this.$helper.deepClone(this.form);
                // form.content = this.parseContent(form.content_raw);
                form.content = form.content_raw;
                form.red_dots_start_time = form.red_dots_start_time ? form.red_dots_start_time / 1000 : '';
                form.red_dots_end_time = form.red_dots_end_time ? form.red_dots_end_time / 1000 : '';

                form.start_time = form.start_time ? form.start_time / 1000 : '';
                form.end_time = form.end_time ? form.end_time / 1000 : '';

                this.loading = true;
                this.$store.dispatch(this.getFormAction(), form).then(res => {
                    this.$message.success(res.data.message);
                    this.$emit('submit');
                }).finally(() => {
                    this.loading = false;
                });
            });
        },
        cancel() {
            this.$emit('cancel');
        },
        syncForm() {
            this.form = this.$helper.deepClone(Object.assign({}, this.formDefault, this.data));
            this.form.red_dots_start_time = this.form.red_dots_start_time ? this.form.red_dots_start_time * 1000 : '';
            this.form.red_dots_end_time = this.form.red_dots_end_time ? this.form.red_dots_end_time * 1000 : '';

            this.form.start_time = this.form.start_time ? this.form.start_time * 1000 : '';
            this.form.end_time = this.form.end_time ? this.form.end_time * 1000 : '';
        },
        handleImageSuccess(res, file) {
            this.form.thumb = res.url;
            this.loading = false
        },
        handleContentImageSuccess(res, file) {
            let quill = this.$refs.editor.quill;
            if (res.url) {
                let length = quill.getSelection().index;
                quill.insertEmbed(length, 'image', res.url);
                quill.setSelection(length+1);
            } else {
                this.$message.error("图片上传失败");
            }
        },
        parseContent(content) {
            // 字体大小
            content = content.replace(/<(\w+) class="ql-size-small">(.*?)<\/(\w+)>/g, '<size=20>$2</size>');
            content = content.replace(/<(\w+) class="ql-size-large">(.*?)<\/(\w+)>/g, '<size=30>$2</size>');
            content = content.replace(/<(\w+) class="ql-size-huge">(.*?)<\/(\w+)>/g, '<size=36>$2</size>');
            // 文本居中
            content = content.replace(/<(\w+) class="ql-align-left">(.*?)<\/(\w+)>/g, '<$1 style="text-align:left">$2</$3>');
            content = content.replace(/<(\w+) class="ql-align-center">(.*?)<\/(\w+)>/g, '<$1 style="text-align:center">$2</$3>');
            content = content.replace(/<(\w+) class="ql-align-right">(.*?)<\/(\w+)>/g, '<$1 style="text-align:right">$2</$3>');

            // 换行
            content = content.replaceAll(/<p><br\/?><\/p>/g, '<br/>');
            // 移除 &nbsp;
            content = content.replaceAll("&nbsp;", " ");
            return content;
        },
        // colorRGBtoHex(color) {
        //     console.log(color)
        //     if (color.substr(0, 1) === '#') return color;
        //     if (color.substr(0, 3) !== 'rgb') return '#000000';
        //     var rgb = color.split(',');
        //     var r = parseInt(rgb[0].split('(')[1]);
        //     var g = parseInt(rgb[1]);
        //     var b = parseInt(rgb[2].split(')')[0]);
        //     var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
        //     return hex;
        // }
    },
    mounted() {
        addQuillTitle();
    },
    created() {
        this.syncForm();
    }
}
</script>


<style lang="scss" scoped>
.item-row {
    margin: 0 0 10px 0;
}

::v-deep {
    .ql-container {
        min-height: 300px;
    }

    .avatar-uploader {
        border-radius: 6px;
        width: 100%;
        //min-height: 100px;
        border: 1px dashed grey;

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100%;
            min-height: 100px;
            //height: 100px;
            line-height: 100px;
            text-align: center;
        }

        .el-upload {

            cursor: pointer;
            position: relative;
            /* overflow: hidden; */
            width: 100%;
            text-align: left;
        }

        img {
            vertical-align: middle;
        }

        .upload-tip {
            background: #eee;
        }
    }

}
</style>

